<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions">
      <template #form="{ form }">
        <el-tabs v-model="activeName" class="w-full" @tab-change="name => tabChange(name, form)">
          <el-tab-pane label="全部" :name="0"></el-tab-pane>
          <el-tab-pane :name="1">
            <template #label>
              未使用 ({{count.not_used}})
            </template>
          </el-tab-pane>
          <el-tab-pane :name="2">
            <template #label>
              已使用 ({{count.used}})
            </template>
          </el-tab-pane>
        </el-tabs>
        <VSelect v-model="form.type" placeholder="编码类型" :options="options.type" multiple collapse-tags
          style="min-width: 160px" />
        <VCascader v-model="form.create_id" placeholder="创建人" multiple collapse-tags style="min-width: 160px" />
        <VGroup>
          <el-select v-model="form.dateRange.type" style="width: 120px">
            <el-option label="创建时间" value="create_time"></el-option>
          </el-select>
          <el-date-picker v-model="form.dateRange.value" type="daterange" value-format="YYYY-MM-DD" range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期" style="max-width: 260px" />
        </VGroup>
        <VGroup>
          <el-select v-model="form.input.type" style="width: 100px">
            <el-option label="商品编码" value="code"></el-option>
          </el-select>
          <el-input v-model="form.input.value" placeholder="请输入" class="w-60" />
        </VGroup>
      </template>
      <template #toolbar_btns>
        <VButton auth="/base/upc/add" type="primary" icon="DocumentAdd" @click="create(tableRef)">添加</VButton>
        <VButton auth="/base/upc/used" :loading="loadings.used" @click="handleBatch('used')">标记已使用</VButton>
        <VButton auth="/base/upc/delete" :loading="loadings.delete" @click="handleBatch('delete')">删除</VButton>
        <VImport :tableRef="tableRef" importUrl="/v1/material/upc/import"
                 v-if="authList.includes('/base/upc/import')"
          downloadUrl="https://xc-base.oss-cn-shenzhen.aliyuncs.com/template/upc.xlsx" class="ml-auto" />
        <VExport auth="/purchase/manage/bill/export" mainKey="cb_id" name="check_bill"
                 v-if="authList.includes('/base/upc/export')"
                 :tableRef="tableRef" task />
      </template>
    </VTable>
    <Add ref="addRef" :options="options" @success="query" />
  </VPage>
</template>
  
<script setup lang="jsx" name="Account">
import api from './api'
import Add from './components/Add'
import VImport from '@/components/VImport'
import { getOption } from '@/api/public'
import { ElMessage, ElMessageBox, countdownEmits } from 'element-plus'

const baseName = 'upc'
const tableRef = ref()
const loadings = reactive({})
const authList = window.BTN_AUTH || []
// 查询
const query = () => {
  tableRef?.value.query()
}

// 新增
const addRef = ref()
const create = () => {
  addRef?.value.open()
}

const activeName = ref(0)
const tabChange = (name, form) => {
  if(name === 0) {
    form.used = [1, 2]
  } else {
    form.used = [name]
  }
  query()
}

// 获取options
const options = ref({})
Promise.all([
  getOption({ type: baseName }).then(res => res.data),
  Promise.resolve({ test: [{ label: '没有数据', value: 1 }] })
]).then(res => {
  options.value = res.reduce((acc, cur) => (((acc = { ...acc, ...cur }), acc)), {})
})

// 批量操作
const handleBatch = (name) => {
  const selection = tableRef.value.$table.getCheckboxRecords()
  if (!selection.length) {
    ElMessage.warning('请先选择行')
    return
  }
  const uc_ids = selection.map(d => d.uc_id)
  const showLoading = () => loadings[name] = true
  const closeLoading = () => loadings[name] = false
  const handle = {
    used: () => {
      showLoading()
      api.used({ uc_ids, used: 2 }).then(res => {
        ElMessage({ type: 'success', message: '操作成功', })
        query()
      }).finally(closeLoading)
    },
    delete: () => {
      ElMessageBox.confirm('是否确认删除？', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          showLoading()
          api.delete({ uc_ids }).then(res => {
            ElMessage({ type: 'success', message: '操作成功', })
            query()
          }).finally(closeLoading)
        })
        .catch(() => {
          ElMessage({ type: 'info', message: '取消操作', })
        })
    },
  }
  handle[name]()
}
// 单行操作
const handleRow = (name, row, rowIndex) => {
  const { uc_id } = row
  const showLoading = (name = 'handle') => {
    loadings[name + rowIndex] = true
  }
  const closeLoading = (name = 'handle') => {
    loadings[name + rowIndex] = false
  }
  const handle = {
    delete: () => {
      ElMessageBox.confirm('是否确认删除？', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          showLoading()
          api.delete({ uc_ids: [uc_id] }).then(res => {
            ElMessage({ type: 'success', message: '操作成功', })
            query()
          }).finally(closeLoading)
        })
        .catch(() => {
          ElMessage({ type: 'info', message: '取消操作', })
        })
    }
  }
  handle[name]()
}

// 列表配置
const count = ref({})
const tableOptions = reactive({
  showHeaderOverflow: false,
  formConfig: {
    data: {
      used: [1, 2],
      input: { type: 'code', value: '' }, // 组合
      dateRange: { type: 'create_time', value: [], range: true }, // 组合
    }
  },
  columns: [
    { type: 'checkbox', fixed: 'left', width: 40 },
    { title: '商品编码', field: 'code', minWidth: 160 },
    { title: '编码类型', field: 'type_name', minWidth: 100 },
    { title: '可用平台', field: 'platform_name', minWidth: 100 },
    {
      title: '使用状态', field: 'used', minWidth: 140, slots: {
        default: ({ row }) => <VStatus status={row.used === 2} auth true-label='已使用' false-label='未使用' />
      }
    },
    { title: '创建人', field: 'create_name', minWidth: 120 },
    { title: '创建时间', field: 'create_time', minWidth: 170 },
    { title: '使用人', field: 'update_name', minWidth: 120 },
    { title: '使用时间', field: 'used_time', minWidth: 170 },
    {
      title: '备注', field: 'remark', minWidth: 120, line: 2
    },
    {
      title: '操作', width: 80, fixed: 'right', slots: {
        default: ({ row, rowIndex }) => {
          return <div>
            <VButton auth="/base/upc/delete" link type="danger" onClick={() => handleRow('delete', row, rowIndex)}>删除</VButton>
          </div>
        }
      }
    }
  ],
  proxyConfig: {
    ajax: {
      query: ({ page, form }) => api.query({ ...form, ...page }).then(res => {
        const { total, data } = res
        count.value = data.count
        return { data: data.list, total }
      })
    }
  }
})
</script>
  